<?php

$page_security = 'SA_SALESPAYMNT';
$path_to_root = "..";
include_once ($path_to_root . "/includes/ui/allocation_cart.inc");
include_once ($path_to_root . "/includes/session.inc");
include_once ($path_to_root . "/includes/date_functions.inc");
include_once ($path_to_root . "/includes/ui.inc");
include_once ($path_to_root . "/includes/banking.inc");
include_once ($path_to_root . "/includes/data_checks.inc");
include_once ($path_to_root . "/sales/includes/sales_db.inc");
//include_once($path_to_root . "/sales/includes/ui/cust_alloc_ui.inc");
include_once ($path_to_root . "/reporting/includes/reporting.inc");
include_once ($path_to_root . "/pittycash/includes/ui/kaskecil_ui.inc");
include_once ($path_to_root . "/pittycash/includes/db/pittycash_db.inc");
include_once ($path_to_root . "/gl/includes/gl_db.inc");
$js = "";
if ($use_popup_windows)
{
    $js .= get_js_open_window(900, 500);
}
if ($use_date_picker)
{
    $js .= get_js_date_picker();
}
add_js_file('payalloc.js');

page(_($help_context = "Pengisian Kas Kecil"), false, false, "", $js);

$row = get_kaskecil();
$kas_kecil_empty = false;
if ($row == null)
{
    $kas_kecil_empty = true;

    // display_error("Kas kecil belum dibentuk.");
}

if (isset($_GET['NewTrans']))
{
    unset($_SESSION['kb_Items'], $_SESSION['lines_kaskecil']);
    $_SESSION['lines_kaskecil'] = array();
}

if (isset($_SESSION['kb_Items']))
    $line_items = $_SESSION['kb_Items'];
else
    $line_items = array();

//var_dump($line_items);
$Refs = new references();
$Ajax->activate('vardum');
$Ajax->activate('table_lines');
if (isset($_POST['AddItemLine']))
{
    $error = 0;
    $bank_id = get_post('bank_id');
    foreach ($_SESSION['lines_kaskecil'] as $line)
    {
        if ($line['bank_id'] == $bank_id)
        {
            $error++;
        }

    }

    if (get_post('bank_id') == '2')
        $error++;

    if (input_num('amount') > get_bank_balance(get_post('bank_id')))
        $error++;

    if ($error == 0)
    {
        $line = array(
            'date_' => get_post('date_'),
            'amount' => input_num('amount'),
            'bank_id' => get_post('bank_id'),
            'no_slip' => get_post('slip'));
        array_push($_SESSION['lines_kaskecil'], $line);

        unset($_POST['date_'], $_POST['amount'], $_POST['bank_id'], $_POST['slip']);
    } else
    {
        display_error('Duplikat akun bank atau dana tidak mencukupi.');
        set_focus('bank_id');
    }
}

if (isset($_POST['UpdateItem']))
{
    $line_no = get_post('LineNo');
    $_SESSION['lines_kaskecil'][$line_no]['date_'] = get_post('date_');
    $_SESSION['lines_kaskecil'][$line_no]['amount'] = get_post('amount');
    $_SESSION['lines_kaskecil'][$line_no]['bank_id'] = get_post('bank_id');
    $_SESSION['lines_kaskecil'][$line_no]['no_slip'] = get_post('slip');
    unset($_POST['date_'], $_POST['amount'], $_POST['bank_id'], $_POST['slip']);
}

if (isset($_POST['CancelItemChanges']))
{
    unset($_POST['date_'], $_POST['amount'], $_POST['bank_id'], $_POST['slip']);
}

$id_del = find_submit('Delete');
if ($id_del > -1)
{
    unset($_SESSION['lines_kaskecil'][$id_del]);
}

div_start('vardum');
//$lines = $_SESSION['lines_kaskecil'];
//var_dump($_SESSION['lines_kaskecil']);
var_dump($_POST);
div_end();

if (isset($_POST['AddItem']))
{
    $new = array(
        'no_note' => get_post('no_note'),
        'acc_id' => get_post('acc_id'),
        'note' => get_post('note'),
        'amount' => input_num('amount'));

    //array_append($line_items,$new);
    //$line_items->
    array_push($line_items, $new);
    $Ajax->activate('kb_Items');

    $_SESSION['kb_Items'] = $line_items;
    unset($_POST);
    //$_POST['line_items'] = $line_items;

}

if (isset($_GET['AddedID']))
{
    $payment_no = $_GET['AddedID'];

    display_notification_centered(_("The customer payment has been successfully entered."));

    submenu_print(_("&Print This Receipt"), ST_CUSTPAYMENT, $payment_no . "-" .
        ST_CUSTPAYMENT, 'prtopt');

    display_note(get_gl_view_str(ST_CUSTPAYMENT, $payment_no, _("&View the GL Journal Entries for this Customer Payment")));

    //	hyperlink_params($path_to_root . "/sales/allocations/customer_allocate.php", _("&Allocate this Customer Payment"), "trans_no=$payment_no&trans_type=12");

    hyperlink_no_params($path_to_root . "/sales/customer_payments.php", _("Enter Another &Customer Payment"));

    display_footer_exit();
}


//----------------------------------------------------------------------------------------------

function can_process()
{
    global $Refs, $kas_kecil_empty;
    $kaskecil = input_num('total');
    $total = 0;

    if (!isset($_SESSION['lines_kaskecil']) || (count($_SESSION['lines_kaskecil'])) ==
        0)
    {
        display_error('Total harus sama dengan kas kecil.');
        return false;
    }

    foreach ($_SESSION['lines_kaskecil'] as $line)
        $total += $line['amount'];

    if ($kaskecil > $total)
    {
        display_error('Total harus sama dengan kas kecil.');
        return false;
    }

    if ($kaskecil < $total)
    {
        display_error('Total harus sama dengan kas kecil.');
        return false;
    }

    return true;
}

if (isset($_POST['AddPaymentItem']) && can_process())
{
    global $Refs, $kas_kecil_empty;
    
    $ref = get_post('pref');
    
    if ($kas_kecil_empty)
        $ref = 'Auto';
    
    
    if (!$kas_kecil_empty)
    { // TODO: edit parameter
        save_pengisian_kas_kecil($ref);        
    }
    
    //display_error($ref); 
//         exit; 
    create_kas_kecil($_SESSION['lines_kaskecil'], $ref);
    //create_kas_kecil($_SESSION['lines_kaskecil'],input_num('total'));

    unset($_POST);
    unset($_SESSION);
    exit;
    //	//Chaitanya : 13-OCT-2011 - To support Edit feature
    //meta_forward($_SERVER['PHP_SELF'], "NewTrans=0");
    //	meta_forward($_SERVER['PHP_SELF'], $new ? "AddedID=$payment_no" : "UpdatedID=$payment_no");
} else
{
    if (isset($_POST['AddPaymentItem']))
        unset($_POST['AddPaymentItem']);
}

//----------------------------------------------------------------------------------------------


//----------------------------------------------------------------------------------------------
start_form();
if ($kas_kecil_empty)
    hidden('total', get_setting_kas_kecil());
if (!$kas_kecil_empty)
{
    start_outer_table(TABLESTYLE2, "width=75%", 5);
    table_section(1);
    $row = get_kaskecil();
    $pRef = $Refs->get_next(ST_RETKASKECIL);

    label_row(_("Reference :"), $pRef);
    label_row("Date Create :", sql2date($row['tglcreate']));
    hidden('pref', $pRef);
    table_section(2);
    label_row(_("Total :"), price_format($row['total']));
    hidden('total', $row['total']);
    label_row(_("Sisa Kas Kecil :"), price_format($row['quota_sisa']));
    table_section(3);
    bank_accounts_list_row(_("From :"), 'bank_account', null, true);
    bank_balance_row($_POST['bank_account']);
    table_section(4);
    label_row("Date :", sql2date(Today()));
    text_row("No. Slip :", 'no_slip', null, 15, 25);
    end_outer_table(1);


    br();
    start_table(TABLESTYLE, "colspan=7 width=75%");
    $th = array(
        _("No"),
        _("No Kas Bon"),
        _("No Nota"),
        _("Tgl Kas Bon"),
        _("Total Nilai Faktur"),
        _("Kode Rek Beban"),
        _("Rekening Beban"));

    table_header($th);

    $total = 0;
    $k = 1; //row colour counter


    $has_marked = false;
    $result = get_kaskecil_detil();
    while ($stock_item = db_fetch($result))
    {
        label_cell($k . ".");
        //$total += $stock_item['amount'];
        label_cell($stock_item['no_kasbon']);
        label_cell($stock_item['no_note']);
        label_cell($stock_item['date']);
        label_cell(price_format($stock_item['amount']), 'align=right');
        label_cell($stock_item['acc_id']);
        label_cell($stock_item['account_name']);
        end_row();
        $k++;
    }

    alt_table_row_color($k);
    $colspan = 3;

    end_table(1);
}

div_start('table_lines');
start_table(TABLESTYLE, "width=70%");
$th_tunai = array(
    "Tanggal",
    "Total",
    "Bank",
    "Balance",
    "No. Slip",
    "",
    "");
display_heading("Penarikan Tunai");
table_header($th_tunai);
$id = find_submit('Edit');
//$lines = $_SESSION['lines_kaskecil'] ;
//var_dump($id);

foreach ($_SESSION['lines_kaskecil'] as $line_no => $line)
{
    if ($id == $line_no)
        continue;
    start_row();
    label_cell($line["date_"]);
    label_cell($line["amount"]);
    $bank = get_bank_account($line["bank_id"]);
    label_cell($bank['bank_account_name']);
    label_cell(get_bank_balance($line["bank_id"]));
    label_cell($line["no_slip"]);
    edit_button_cell("Edit$line_no", 'Ubah', 'Edit baris input');
    delete_button_cell("Delete$line_no", 'Hapus', 'Hapus baris input');
    end_row();
}

if ($id > -1)
{
    $_POST['date_'] = $_SESSION['lines_kaskecil'][$id]['date_'];
    $_POST['amount'] = $_SESSION['lines_kaskecil'][$id]['amount'];
    $_POST['bank_id'] = $_SESSION['lines_kaskecil'][$id]['bank_id'];
    $_POST['slip'] = $_SESSION['lines_kaskecil'][$id]['no_slip'];
}
start_row();
date_cells(null, 'date_');
amount_cells(null, 'amount');
bank_accounts_list_cells(null, 'bank_id', null, true);
//div_start('bal');
label_cells(null, get_bank_balance(get_post("bank_id")));
//div_end();
text_cells(null, 'slip');
if ($id > -1)
{
    button_cell('UpdateItem', _("Update"), _('Confirm changes'), ICON_UPDATE);
    button_cell('CancelItemChanges', _("Cancel"), _('Cancel changes'), ICON_CANCEL);
    hidden('LineNo', $id);
} else
    submit_cells('AddItemLine', "Tambah Item", "colspan=2 align='center'", _('Add new item to document'), true);
end_row();
end_table(1);
div_end();
submit_center('AddPaymentItem', _("Approve"), true, '', 'default');

br();

end_form();
end_page();

?>